package cn.wolfcode.wolf2w.service.impl;


import cn.wolfcode.wolf2w.domain.TravelComment;
import cn.wolfcode.wolf2w.query.TravelCommentQueryObject;
import cn.wolfcode.wolf2w.repository.TravelCommentRepository;
import cn.wolfcode.wolf2w.service.ITravelCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
//@Transactional mongodb事务必须复制集方式
public class TravelCommentServiceImpl implements ITravelCommentService {
    @Autowired
    private TravelCommentRepository repository;
    @Autowired
    private MongoTemplate template;

    @Override
    public void save(TravelComment travelComment) {
        travelComment.setId(null);//防止游标
        travelComment.setCreateTime(new Date());
        if (StringUtils.hasLength(travelComment.getRefComment().getId())) {
            TravelComment travelComment1 = this.get(travelComment.getRefComment().getId());
            travelComment.setRefComment(travelComment1);
        }
        repository.save(travelComment);
    }

    @Override
    public void update(TravelComment travelComment) {
        repository.save(travelComment);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public TravelComment get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<TravelComment> list() {
        return repository.findAll();
    }

    @Override
    public Page<TravelComment> query(TravelCommentQueryObject qo) {
        //查询的条件对象
        Query query = new Query();
        //拼接条件
        long count = template.count(query, TravelComment.class);//计算一共有多少条数据 query 为无条件 totalCount  集合MOngoDb
        if (count == 0) {
            return Page.empty();//空的页面对象
        }
        //分页加排序---->条件拼接
        PageRequest pageRequest = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        //把条件放入查询对象中
        query.with(pageRequest);
        //查询当前结果集template.find
        List<TravelComment> list = template.find(query, TravelComment.class);
        //PageImpl等价于之前的PageResult
        return new PageImpl<>(list, pageRequest, count);//PageResult原生的  pageRequest当前页  多少条数
        //PageHadler  分页插件的
    }

    @Override
    public List<TravelComment> findByTraveId(String travelId) {
        List<TravelComment> byTraveId = repository.findByTravelId(travelId);
        return byTraveId;
    }
}